package com.apes.fn.scm.report.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.function.Predicate;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-03-08 10:35
 **/
public class SalesReportUtils {


    public static void appendCondition(StringBuffer sf, JSONObject param, String prefix, String... permissionConditions) {
        appendCondition(sf, param, prefix, false, permissionConditions);
    }

    /**
     * 自动拼接要求的条件
     *
     * @param sf                   sql
     * @param param                入参
     * @param prefix               条件字段前缀
     * @param must                 是否必须
     * @param permissionConditions 允许的条件字段
     */
    public static void appendCondition(StringBuffer sf, JSONObject param, String prefix, boolean must, String... permissionConditions) {

        for (String permissionCondition : permissionConditions) {
            Object condition = param.get(permissionCondition);
            if (condition == null) {
                if (must) throw new RuntimeException("缺少必要参数条件:" + permissionCondition);
            } else if (condition instanceof List) {
//                appendConditionList(sf,prefix,permissionCondition, (List) condition);
                sf.append(" and " + prefix + permissionCondition + " in( :" + permissionCondition + " )");
            } else if (condition instanceof JSONObject) {
//                List<Object> objects = Arrays.asList(condition);
//                appendConditionList(sf,prefix,permissionCondition, objects);
                sf.append(" and " + prefix + permissionCondition + " in( :" + permissionCondition + " )");
            } else if (condition instanceof Date) {
//                List<Object> objects = Arrays.asList(condition);
//                appendConditionList(sf,prefix,permissionCondition, objects);
                sf.append(" and " + prefix + permissionCondition + " >=  :" + permissionCondition + "_S ");
                sf.append(" and " + prefix + permissionCondition + " <=  :" + permissionCondition + "_E ");
            } else {
                sf.append(" and " + prefix + permissionCondition + " = :" + permissionCondition+" ");
            }
        }
    }

    /**
     * 单天转化为范围
     *
     * @param jo
     * @param key
     */
    public static void dateTimeToDateRange(JSONObject jo, String key) {
        Date date = jo.getDate(key);
        if (date==null)throw new RuntimeException("缺少必备参数:"+key);
        //去除时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateSatrt = sdf.format(date);
        //获取后一天
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        calendar.add(Calendar.DATE, 1);

        jo.put("DATE_START", dateSatrt);
        jo.put("DATE_END", dateSatrt);
    }
    /**
     * 单天转化为范围下一天
     *
     * @param jo
     * @param key
     */
    public static void dateTimeToDateNext(JSONObject jo, String key) {
        Date date = jo.getDate(key);
        if (date==null)throw new RuntimeException("缺少必备参数:"+key);
        //去除时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateSatrt = sdf.format(date);
        //获取后一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);

        jo.put("DATE_START", date);
        jo.put("DATE_END", calendar.getTime());
    }

    /**
     * 单天转化为范围
     *
     * @param jo
     * @param key
     */
    public static void getNextDate(JSONObject jo, String key,String resultKey) {
        Date date = jo.getDate(key);
        if (date==null)throw new RuntimeException("缺少必备参数:"+key);
        //去除时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateSatrt = sdf.format(date);
        //获取后一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);

        try {
            jo.put(resultKey+"_S", sdf.parse(dateSatrt));
        } catch (ParseException e) {
            throw new RuntimeException("格式转换错误!!");
        }
        jo.put(resultKey+"_E", calendar.getTime());
    }

    /**
     *
     * @param sf 原SQL
     * @param param 入参
     * @param indexSTR  用于替换的字符串
     * @param groupTypeList 分组函数字段 索引0为函数 索引1为前缀
     * @param strings 用于分组的字段
     */
    public static void appendGroup(StringBuffer sf,JSONObject param,String indexSTR,List<List<String>> groupTypeList, String[]... strings) {
        StringBuilder fieldList = new StringBuilder();
        StringBuilder groupList = new StringBuilder();
        //拼接分组字段
        for (int i = 0; i < strings.length; i++) {
            String[] string = strings[i];
            if (string.length>0&&param.containsKey(string[0])){
                for (int s = 1; s < string.length; s++) {
                    fieldList.append(" "+string[s]+",");
                    groupList.append(" "+string[s]+",");
                }
            }
        }
        //处理标点符号和分组标记
        if (groupList.length()>0) {
            String sql = sf.toString().toUpperCase();
            if (!sql.contains("GROUP BY")) {
                sf.append(" GROUP BY ");
            }else {
                sf.append(", ");
            }
            groupList.delete(groupList.length()-1,groupList.length());
        }
        //拼接分组函数
        for (List<String> list : groupTypeList) {
            ArrayList<String> arrayList = new ArrayList<String> (list);
            String function = arrayList.remove(0);
            String perfix = arrayList.remove(0);
            for (String s : arrayList) {
                fieldList.append(" "+function+"("+perfix+s+")"+s+",");
            }
        }

        int index = sf.indexOf(indexSTR);
        sf.replace(index,index+(indexSTR.length()),fieldList.toString());
        sf.append(groupList.toString());
//        System.out.println(sf.toString());
    }

    public void appendConditionList(StringBuffer sf, String prefix, String permissionCondition, List conditionList) {
        sf.append(" and " + prefix + permissionCondition + " in ( ");
        String type = "";
        if (conditionList.isEmpty()) return;
        Object o = conditionList.get(0);
        if (o instanceof String) {
            type = "String";
        } else {
            type = "Int";
        }
        switch (type) {
            case "String":
                sf.append("'" + o + "'");
                break;
            case "Int":
                sf.append(o);
                break;
        }

        for (Object condition : conditionList) {
            switch (type) {
                case "String":
                    sf.append(",'" + condition + "'");
                    break;
                case "Int":
                    sf.append("," + condition);
                    break;
            }
        }
        sf.append(" )");
    }

    /**
     * 仅适用于传某天的参数 获取月初和月尾
     *
     *
     * @param param
     */
    public static void dateTimeGetMonth(JSONObject param, String key, String target) {
        Date date = param.getDate(key);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH)+1;
        int year = calendar.get(Calendar.YEAR);
        LocalDate startTime = LocalDate.of(year, month, 1);
        Date from = Date.from(startTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        param.put(target, from);
        param.put(target+"_S", from);
        calendar.setTime(from);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DATE,-1);
        param.put(target+"_E", calendar.getTime());
    }
    /**
     * 开始日期结束日期格式化成月初月尾
     *
     * @param param
     */
    public static void dateRangChangeToFirstDayAndLastDay(JSONObject param) {
        Date dateS = param.getDate("DATE_START");
        Date dateE = param.getDate("DATE_END");
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(dateS);
        int month = calendar.get(Calendar.MONTH)+1;
        int year = calendar.get(Calendar.YEAR);
        LocalDate startTime = LocalDate.of(year, month, 1);
        Date from = Date.from(startTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

        param.put("DATE_START", sdf.format(from));
        calendar.setTime(dateE);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DATE,calendar.get(Calendar.DATE)*-1);
        dateE = calendar.getTime();

        param.put("DATE_END",sdf.format(dateE));
        param.put("FORMAT","MM");

    }
    /**
     * 开始日期结束日期格式化成年初年底
     *
     * @param param
     */
    public static void dateRangChangeToFirstDayAndLastDayByYear(JSONObject param) {
        Date dateS = param.getDate("DATE_START");
        Date dateE = param.getDate("DATE_END");
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(dateS);
        int month = 1;
        int year = calendar.get(Calendar.YEAR);
        LocalDate startTime = LocalDate.of(year, month, 1);
        Date from = Date.from(startTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

        param.put("DATE_START", sdf.format(from));
        calendar.setTime(dateE);
        month = 12;
        year = calendar.get(Calendar.YEAR);
        startTime = LocalDate.of(year, month, 1);
        from = Date.from(startTime.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        calendar.setTime(from);
        calendar.add(Calendar.MONTH,1);
        calendar.add(Calendar.DATE,-1);

        param.put("DATE_END", sdf.format(calendar.getTime()));
        param.put("FORMAT", "YEAR");

    }

    /**
     * 返回App所需格式 key:{name:value}
     *
     * @param resultJson
     * @param nameLis
     * @return
     */
    public static JSONObject formatJsonToApp(JSONObject resultJson, String... nameLis) {
        JSONObject newResultJson = new JSONObject();
        if (nameLis.length % 2 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        for (int i = 0; i < nameLis.length; i++) {
            String name;
            String key;
            String value;
            if (i % 2 == 0) {
                key = nameLis[i];
                value = resultJson.getString(nameLis[i]);
                name = nameLis[i + 1];
                putJson(newResultJson, key, name, value);
            }
        }
        return newResultJson;
    }


    /**
     * 获取需要返回的数据
     *
     * @param resultJson
     * @param nameLis
     * @return
     */
    public static JSONObject filterJson(JSONObject resultJson, String... nameLis) {
        JSONObject newResultJson = new JSONObject();
        for (int i = 0; i < nameLis.length; i++) {
            String name;
            String key;
            String value;
            if (i % 2 == 0) {
                key = nameLis[i];
                value = resultJson.getString(key);
                name = nameLis[i + 1];
//                putJson(newResultJson, key, name, value);
                newResultJson.put(name,value==null?0:value);
            }
        }
        return newResultJson;
    }

    /**
     * 计算返回结果
     *
     * @param resultJson
     * @param coulcomList  [0]第一位数字 [1]第二位数字 [2]计算方式 [4]计算出结果的字段名 [5] 中文名
     * @return
     */
    public static JSONObject calculateResultJsonPercent(JSONObject resultJson, String... coulcomList) {
        if (resultJson.isEmpty()) return resultJson;
        if (coulcomList.length % 5 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        for (int i = 0; i < coulcomList.length; i++) {
            if (i % 5 == 0) {
                Double val1 = getJsonDoubleValue(getResultJsonValue(resultJson, coulcomList[i]));
                Double val2 = getJsonDoubleValue(getResultJsonValue(resultJson, coulcomList[i + 1]));

                calculate(resultJson, i, val1, val2, coulcomList);
            }
        }
        return resultJson;
    }
    /**
     * 计算返回结果
     *
     * @param jsonArray
     * @param operation
     * @return
     */
    public static Double calculateResultArraySum(JSONArray jsonArray, String filed,String operation) {
        Double result =0D;
        if (jsonArray.isEmpty()) return result;

        for (int j = 0; j < jsonArray.size(); j++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(j);
            Double val1 = getJsonDoubleValue(getResultJsonValue(jsonObject, filed));
            result =calculate( val1, result, operation);
        }

        return result;
    }

    public static Object getResultJsonValue(JSONObject resultJson, String key) {
        Object o = resultJson.get(key);
        Object result ;
        if (o instanceof JSONObject){
            result = ((JSONObject) o).get("value");
        }else if (o instanceof HashMap){
            result = ((HashMap) o).get("value");
        }else {
            result = o;
        }
        return result;
    }

    /**
     * APP要求格式
     * key:{name:value}
     *
     * @param resultJson
     * @param key
     * @param name
     * @param value
     */
    private static void putJson(JSONObject resultJson, String key, String name, Object value) {
        if (value==null)value = "0";
        resultJson.put(key, MapUtil.mapper("name", name, "value", value+""));
    }

    public static Double getJsonDoubleValue(Object resultJsonValue) {
        Double val;
        if (resultJsonValue instanceof Double) {
            val = (Double) resultJsonValue;
        } else if (resultJsonValue instanceof String) {
            val = Double.parseDouble((String) resultJsonValue);
        }else if (resultJsonValue instanceof BigDecimal) {
            val = ((BigDecimal) resultJsonValue).doubleValue();
        } else {
            throw new RuntimeException("未知类型:" + resultJsonValue.getClass());
        }
        return val;
    }

    /**
     * 格式化数组为折线图
     * 没有的天数 自动填充默认值
     * @param jsonArray
     * @param jo 入参
     * @param key X轴日期
     * @param elementList i = 字段名 ,i+1 = 中文名 , i+2 = 默认值
     * @return
     */
    public static JSONObject jsonArrayToLineStack(JSONArray jsonArray,JSONObject jo,String key,String... elementList){
        if (elementList.length % 3 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        JSONObject dataJson = new JSONObject();
//        if (jsonArray.isEmpty()) return dataJson;
        int type = 0;
        if ("day".equals(jo.getString("type"))){
            type = Calendar.DATE;
        }else if("month".equals(jo.getString("type"))){
            type = Calendar.MONTH;
        }else {
            type = Calendar.WEEK_OF_YEAR;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfweek = new SimpleDateFormat("yyyy-ww");
        Date date_start = jo.getDate("DATE_START");
        Date date_end = jo.getDate("DATE_END");
        calendar.setTime(date_start);
        endDate.setTime(date_end);

        endDate.add(type,1);
        date_end=endDate.getTime();

        while (date_start.before(date_end)){
            Date finalDate_start = date_start;
            //判断是否有当天/周/月数据
            JSONObject jsonObject = jsonArray.stream().map(o -> (JSONObject) o)
                    .filter(j -> {
                                if (j.get(key) instanceof Date) {
                                    return j.getDate(key).getTime() == finalDate_start.getTime();
                                } else if (j.get(key) instanceof String) {
                                    return j.getString(key).equals(sdfweek.format(finalDate_start));
                                }else {
                                    return false;
                                }
                            }
                    ).findFirst().orElse(new JSONObject());
            //如果没有当前天数的日期 则填充默认值
            if (jsonObject.isEmpty()) {
                for (int i = 0; i < elementList.length; i++) {
                    if (i % 3 ==0){
                        String s = elementList[i + 2];
                        if (s.equals(key)){
                            s = sdf.format(date_start);
                        }
                        String string = jsonObject.containsKey(elementList[i])?jsonObject.getString(elementList[i]): s;
                        JSONObject object = dataJson.getJSONObject(elementList[i]);
                        JSONArray array = new JSONArray();
                        if (object != null)array = object.getJSONArray("data");
                        array.add(string);
                        dataJson.put(elementList[i],MapUtil.mapper("name",elementList[i+1],"data",array));
                    }
                }
            }else {//有就正常取值
                for (int i = 0; i < elementList.length; i++) {
                    if (i % 3 ==0){
                        String string = jsonObject.getString(elementList[i]);
                        JSONObject object = dataJson.getJSONObject(elementList[i]);
                        JSONArray array = new JSONArray();
                        if (object != null)array = object.getJSONArray("data");
                        array.add(string);
                        dataJson.put(elementList[i],MapUtil.mapper("name",elementList[i+1],"data",array));
                    }
                }
            }
            calendar.add(type,1);
            date_start = calendar.getTime();
        }

        //Map转List<JSONObject>
        List<JSONObject> dataList = new ArrayList<>();
        JSONObject series = new JSONObject();
        Iterator<String> iterator = dataJson.keySet().iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            JSONObject jsonObject = dataJson.getJSONObject(next);
            dataList.add(jsonObject);
        }
        series.put("series",dataList);
        return series;
    }

    public static void changeTargetName(JSONObject jsonObject,String... elementList){
        if (jsonObject.isEmpty()) return ;
        if (elementList.length % 2 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        for (int i = 0; i < elementList.length; i++) {
            if (i % 2 ==0){
                Object o = jsonObject.get(elementList[i]);
                jsonObject.remove(elementList[i]);
                jsonObject.put(elementList[i+1],o);
            }
        }
    }
    //格式化数组为柱线混图
    public static JSONObject jsonArrayToLineOrBarStack(JSONArray jsonArray,JSONObject jo,String key,String... elementList){
        JSONObject dataJson = new JSONObject();
        if (jsonArray.isEmpty()) return dataJson;
        if (elementList.length % 4 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfweek = new SimpleDateFormat("yyyy-ww");
        Calendar calendar = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        Date date_start = jo.getDate("DATE_START");
        Date date_end = jo.getDate("DATE_END");

        calendar.setTime(date_start);
        endDate.setTime(date_end);
        int type = 0;
        if ("day".equals(jo.getString("type"))){
            type = Calendar.DATE;
        }else if("month".equals(jo.getString("type"))){
            type = Calendar.MONTH;
        }else {
            type = Calendar.WEEK_OF_YEAR;
        }
        endDate.add(type,1);
        date_end=endDate.getTime();

        while (date_start.before(date_end)){
            Date finalDate_start = date_start;
            String format = sdfweek.format(finalDate_start);
            JSONObject jsonObject = jsonArray.stream()
                    .map(o -> (JSONObject) o).filter(j -> {
                                if (j.get(key) instanceof Date) {
                                    return j.getDate(key).getTime() == finalDate_start.getTime();
                                } else if (j.get(key) instanceof String) {
                                    System.out.println(j.getString(key)+" EQ "+format);
                                    return j.getString(key).equals(format);
                                } else {
                                    return false;
                                }
                            }
                    ).findFirst().orElse(new JSONObject());
            //如果没有当前天数的日期 则填充默认值
            if (jsonObject.isEmpty()) {
                for (int i = 0; i < elementList.length; i++) {
                    if (i % 4 ==0){
                        String s = elementList[i + 3];
                        if (s.equals(key)){
                            s = sdf.format(date_start);
                        }
                        String string = jsonObject.containsKey(elementList[i])?jsonObject.getString(elementList[i]): s;
                        JSONObject object = dataJson.getJSONObject(elementList[i]);
                        JSONArray array = new JSONArray();
                        if (object != null)array = object.getJSONArray("data");
                        array.add(string);
                        dataJson.put(elementList[i],MapUtil.mapper("name",elementList[i+1],"type",elementList[i+2],"data",array));
                    }
                }
            }else {//有就正常取值
                for (int i = 0; i < elementList.length; i++) {
                    if (i % 4 ==0){
                        String s = elementList[i + 3];
                        String string = jsonObject.containsKey(elementList[i])?jsonObject.getString(elementList[i]): s;
                        JSONObject object = dataJson.getJSONObject(elementList[i]);
                        JSONArray array = new JSONArray();
                        if (object != null)array = object.getJSONArray("data");
                        array.add(string);
                        dataJson.put(elementList[i],MapUtil.mapper("name",elementList[i+1],"type",elementList[i+2],"data",array));
                    }
                }
            }
            calendar.add(type,1);
            date_start = calendar.getTime();
        }

        //Map转List<JSONObject>
        List<JSONObject> dataList = new ArrayList<>();
        JSONObject series = new JSONObject();
        Iterator<String> iterator = dataJson.keySet().iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            JSONObject jsonObject = dataJson.getJSONObject(next);
            dataList.add(jsonObject);
        }
        series.put("series",dataList);
        return series;
    }

    public static void changeVal2ToVal1Name(JSONObject jsonObject,Boolean remove,String... elementList){
        if (jsonObject.isEmpty()) return ;
        if (elementList.length % 2 != 0) {
            throw new RuntimeException("不正确的输入列");
        }
        for (int i = 0; i < elementList.length; i++) {
            if (i % 2 ==0){
                if (jsonObject.containsKey("series")){
                    JSONArray series = jsonObject.getJSONArray("series");
                    Object value = null;
                    Object keyO = null;
                    Object valueO = null;
                    String key = null;
                    for (Object o : series) {
                        JSONObject jo = (JSONObject) o;
                        String name = jo.getString("name");
                        if (name.equals(elementList[i])){
                            value = jo.get("data");
                            valueO = o;
                        }else if(name.equals(elementList[i+1])) {
                            key = jo.getJSONArray("data").getString(0);
                            keyO = o;
                        }
                    }
                    series.remove(valueO);
                    if (remove)series.remove(keyO);
                    if (key!=null)series.add(MapUtil.mapper("name",key,"data",value));
                }else {
                    String val1Key = jsonObject.getString(elementList[i]);
                    String val2Key = jsonObject.getString(elementList[i+1]);
                    JSONObject val1 = jsonObject.getJSONObject(val1Key);
                    JSONObject val2 = jsonObject.getJSONObject(val2Key);
                    if (remove)jsonObject.remove(val2Key);
                    putJson(jsonObject,val1Key,val2.getString("data"),val1.getString("data"));
                }

            }
        }
    }
    /**
     * 计算返回结果
     * 取每个数组中某个字段计算
     *
     * @param resultJson
     * @param coulcomList
     * @return
     */
//    public static JSONObject calculateResultJson(JSONObject resultJson,JSONArray source, String... coulcomList) {
//        if (resultJson.isEmpty()) return resultJson;
//        if (coulcomList.length % 4 != 0) {
//            throw new RuntimeException("不正确的输入列");
//        }
//        for (int i = 0; i < coulcomList.length; i++) {
//            if (i % 4 == 0) {
////                for (int j = 0; j < source.size(); j++) {
////                    JSONObject jsonObject1 = (JSONObject) source.get(j);
////                    Double val1 = getJsonDoubleValue(getResultJsonValue(resultJson, coulcomList[i]));
////                    Double val2 = getJsonDoubleValue(getResultJsonValue(jsonObject1, coulcomList[i]));
////                    calculate(resultJson, i, val1, val2, coulcomList);
////                }
//            }
//        }
//        return resultJson;
//    }

    private static void calculate(JSONObject resultJson, int i, Double val1, Double val2, String[] coulcomList) {
        String operation = coulcomList[i + 2];
        String newKey = coulcomList[i + 3];
        String newName = coulcomList[i + 4];

        switch (operation) {
            case "/":
                if (val2!=0)putJson(resultJson, newKey, newName, Arith.round((val1 / val2) * 100, 2));
                if (val2==0)putJson(resultJson, newKey, newName, 100);
                break;
            case "*":
                putJson(resultJson, newKey, newName, Arith.round(val1 * val2,2));
                break;
            case "+":
                putJson(resultJson, newKey, newName, Arith.round(val1 + val2,2));
                break;
            case "-":
                putJson(resultJson, newKey, newName, Arith.round(val1 - val2,2));
                break;
            default:
                throw new RuntimeException("非法操作符");
        }
    }
    private static Double calculate(Double val1, Double val2, String operation) {

        switch (operation) {
            case "/":
                if (val2!=0)return Arith.round((val1 / val2) * 100, 2);
                if (val2==0)return 100d;
                break;
            case "*":
                return val1 * val2;
            case "+":
                return val1 + val2;
            case "-":
               return val1 - val2;
            default:
                throw new RuntimeException("非法操作符");
        }
        return 0d;
    }

    public static void dateRangeFindWeekRange(JSONObject jo){
        Date dateS = jo.getDate("DATE_START");
        Date dateE = jo.getDate("DATE_END");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateS);
        int satrt = calendar.get(Calendar.WEEK_OF_YEAR);
        jo.put("YEAR",calendar.get(Calendar.YEAR));
        calendar.setTime(dateE);
        int end = calendar.get(Calendar.WEEK_OF_YEAR);
        jo.put("YEAR_WEEK",dateS);
        jo.put("YEAR_WEEK_S",satrt);
        jo.put("YEAR_WEEK_E",end);
    }

    public static JSONObject drawPie(JSONArray rankArray,String key,String... extraList){
        JSONObject result = new JSONObject();
        JSONArray dataArray = new JSONArray();
        for (Object o : rankArray) {
            JSONObject rank = (JSONObject) o;
            JSONObject field = rank.getJSONObject(key);
            JSONObject data = new JSONObject();
            data.putAll(field);
            JSONArray extraArray = new JSONArray();
            for (String s : extraList) {
                JSONObject extra = rank.getJSONObject(s);
                extraArray.add(extra);
            }
            if (extraList.length>0)data.put("extra",extraArray);
            dataArray.add(data);
        }
        result.put("series",dataArray);
        return result;
    }

    /**
     * 解析 周范围 字符
     *
     * @param jo
     * @param key
     */
    public static void dateTimeGetWeekRange(JSONObject jo,String key){
        String startDateStr = jo.getString(key+"_START");
        String endDateStr = jo.getString(key+"_END");

        Calendar startCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-'W'ww", Locale.US);
            startCal.setTime(sdf.parse(startDateStr));
            endCal.setTime(sdf.parse(endDateStr));
        } catch (ParseException e) {
            throw new RuntimeException("解析错误:"+e.getMessage());
        }

        // 设置每周的第一天为周一
        startCal.setFirstDayOfWeek(Calendar.MONDAY);
        endCal.setFirstDayOfWeek(Calendar.MONDAY);
        jo.put("DATE_START",startCal.getTime());
        jo.put("DATE_END",endCal.getTime());
        int weeks = getWeeksBetween(startCal, endCal);
        JSONArray result = new JSONArray();

        SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-ww", Locale.US);
        for (int i = 0; i < weeks; i++) {
            String dateStr = outputSdf.format(startCal.getTime());
            result.add(dateStr);

            startCal.add(Calendar.WEEK_OF_YEAR, 1);
        }

        jo.put("YEAR_WEEK",result);

    }

    public static int getWeeksBetween(Calendar startCal, Calendar endCal) {
        int weeks = 0;
        Calendar temp = Calendar.getInstance();
        long l = startCal.getTime().getTime() - 1;
        temp.setTime(new Date(l));
        while (temp.before(endCal)) {
            weeks++;
            temp.add(Calendar.WEEK_OF_YEAR, 1);
            if (weeks>10000)throw new RuntimeException("超出大小");
        }

        return weeks;
    }
}
